<script lang="ts" setup>
import { Modal, message } from 'ant-design-vue';
import { useSendMessage } from '../useSendMessage';
import { useStatisticalStore } from '@/store/modules/dcp/message_management/statistical';
import useUserStore from '@/store/modules/user';
import { getMessageByPageAndName, getMessageHistoryDown, getMessageHistoryUP } from '@/api/modules/rbac/dcp/message_management';

const userStore = useUserStore();
const userId = ref<string>('');
const account = ref<string>('');
const condition = ref<string>('');
const sort = ref<any>('3');
const data = ref<any[]>([]);
const loading = ref<boolean>(false);
const loadingBydate = ref<boolean>(false);
const allColumns: any = [
  {
    title: '手机号',
    dataIndex: 'accNbr',
    key: 'accNbr',
    width: '15%',
    align: 'center',
  },
  {
    title: '发送信息',
    dataIndex: 'orderContent',
    key: 'orderContent',
    align: 'center',
  },
  {
    title: '发送时间',
    dataIndex: 'requestTime',
    key: 'requestTime',
    width: '30%',
    align: 'center',
  },
  {
    title: '发送人',
    dataIndex: 'sender',
    key: 'sender',
    width: '15%',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'state',
    key: 'state',
    width: '15%',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: '10%',
    align: 'center',
  },
];
function showRoleColumn() {
  account.value = userStore.account;
  if (account.value === '管理员') {
    return true;
  }
  return false;
}
const columns: any = computed(() => {
  return allColumns.filter((column: any) => {
    const flag = showRoleColumn();
    if (!flag && column.title === '操作') {
      return false;
    }
    return true;
  });
});
function extractedText(name: string) {
  if (name !== '' && name !== null) {
    const parts = name.split('(');
    return parts[0];
  }
  return '';
}
const total = ref<number>(0);
const current = ref<number>(1);
const pageSize = ref<number>(10);
async function getData() {
  loading.value = true;
  if (account.value === '管理员') {
    if (sort.value === '1') {
      await getMessageHistory(current.value, pageSize.value).then((res: any) => {
        data.value = res.data.records;
        total.value = res.data.total;
      }).finally(() => {
        loading.value = false;
      });
    }
    else if (sort.value === '2') {
      await getMessageHistoryUP(current.value, pageSize.value).then((res: any) => {
        data.value = res.data.records;
        total.value = res.data.total;
      }).finally(() => {
        loading.value = false;
      });
    }
    else if (sort.value === '3') {
      await getMessageHistoryDown(current.value, pageSize.value).then((res: any) => {
        data.value = res.data.records;
        total.value = res.data.total;
      }).finally(() => {
        loading.value = false;
      });
    }
  }
  else {
    await getMessageByPageAndName(current.value, pageSize.value, condition.value).then((res: any) => {
      data.value = res.data.records;
      total.value = res.data.total;
    }).finally(() => {
      loading.value = false;
    });
  }
}
defineExpose({
  getData,
});
onMounted(async () => {
  // 获取发送人信息
  userId.value = userStore.userId;
  account.value = userStore.account;
  condition.value = `${account.value}(${userId.value})`;
  useStatisticalStore().getAllMsg();
  getData();
});
async function handleTableChange(pagination: any) {
  pageSize.value = pagination.pageSize;
  current.value = pagination.current;
  getData();
}
const way = ref<string>('server');
async function reSend(record: any) {
  if (record.accNbr === '') {
    message.error('无法获取手机号！');
    return;
  }
  if (way.value === 'thisDevice') {
    useSendMessage().sendMessageHistory(record.accNbr, record.orderContent, record.requestTime, record.id);
  }
  else {
    useSendMessage().sendMessageByServerHistory(record.accNbr, record.orderContent, record.requestTime, record.id);
  }
  getData();
}

function info(content: string) {
  Modal.info({
    title: () => '具体内容',
    content: () => h('div', {}, [
      h('p', content),
    ]),
  });
}

const activeKey = ref<string>('1');
const date = ref<any>([]);
const dataBydate = ref<any[]>([]);
watch(
  () => date.value,
  () => {
    if (data.value.length > 0 && activeKey.value === '5') {
      dataBydate.value = useStatisticalStore().getMsgByDate(activeKey.value, date.value);
    }
  },
  { deep: true },
);

watch(
  () => activeKey.value,
  async () => {
    if (activeKey.value !== '5' && activeKey.value !== '1') {
      loadingBydate.value = true;
      dataBydate.value = await useStatisticalStore().getMsgByDate(activeKey.value);
      loadingBydate.value = false;
    }
    else {
      dataBydate.value = [];
    }
  },
  { deep: true },
);
watch(
  () => sort.value,
  async () => {
    getData();
  },
  { deep: true },
);
</script>

<template>
  <div>
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            短信发送数据
          </div>
        </a-space>
      </div>
      <div class="right">
        <!-- <a-radio-group v-model:value="way">
          <a-radio-button value="thisDevice">
            本机发送
          </a-radio-button>
          <a-radio-button value="server">
            服务器发送
          </a-radio-button>
        </a-radio-group> -->
      </div>
    </div>
    <div class="content">
      <a-tabs v-model:activeKey="activeKey" tab-position="top">
        <a-tab-pane key="1" tab="全部" />
        <a-tab-pane key="2" tab="今日" force-render />
        <a-tab-pane key="3" tab="近一周" />
        <a-tab-pane key="4" tab="近一月" />
        <a-tab-pane key="5" tab="精确日期查询" />
        <template #tabBarExtraContent>
          <div v-if="activeKey === '1'">
            <a-radio-group v-model:value="sort">
              <a-radio-button value="2">
                升序
              </a-radio-button>
              <a-radio-button value="3">
                降序
              </a-radio-button>
            </a-radio-group>
          </div>
          <a-range-picker v-if="activeKey === '5'" v-model:value="date" />
        </template>
      </a-tabs>
      <a-table
        v-if="activeKey === '1'" :columns="columns" :data-source="data" row-key="id" class="d-table"
        :loading="loading" :pagination="{ pageSize, showQuickJumper: true, total }" @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'sender'">
            {{ extractedText(record.sender) }}
          </template>
          <template v-if="column.dataIndex === 'orderContent'">
            <div style="max-width: 300px;margin: 0 auto;">
              <span
                style="display: block;overflow: hidden;text-align: center;text-overflow: ellipsis;white-space: nowrap; cursor: pointer;"
                @click="info(record.orderContent)"
              >
                {{ record.orderContent }}
              </span>
            </div>
          </template>
          <template v-if="column.dataIndex === 'state'">
            <span v-if="record.state === '发送成功'" style="color: #47d232;">
              发送成功
            </span>
            <span v-else style="color: red; cursor: pointer;" @click="info(record.state)">发送失败</span>
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <span v-if="record.state !== '发送成功'">
              <a-space>
                <a-button type="link" @click="reSend(record)">重新发送</a-button>
              </a-space>
            </span>
          </template>
        </template>
      </a-table>
      <a-table
        v-else-if="dataBydate.length > 0 || activeKey === '5'" :columns="columns" :data-source="dataBydate" row-key="id" class="d-table"
        :loading="loadingBydate"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'sender'">
            {{ extractedText(record.sender) }}
          </template>
          <template v-if="column.dataIndex === 'orderContent'">
            <div style="max-width: 300px;margin: 0 auto;">
              <span
                style="display: block;overflow: hidden;text-align: center;text-overflow: ellipsis;white-space: nowrap; cursor: pointer;"
                @click="info(record.orderContent)"
              >
                {{ record.orderContent }}
              </span>
            </div>
          </template>
          <template v-if="column.dataIndex === 'state'">
            <span v-if="record.state === '发送成功'" style="color: #47d232;">
              发送成功
            </span>
            <span v-else style="color: red; cursor: pointer;" @click="info(record.state)">发送失败</span>
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <span v-if="record.state !== '发送成功'">
              <a-space>
                <a-button type="link" @click="reSend(record)">重新发送</a-button>
              </a-space>
            </span>
          </template>
        </template>
      </a-table>
      <div v-else>
        <a-spin />
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 31px;
  margin-bottom: 10px;

  .pjTitle {
    padding-left: 15px;
    background: url("@/assets/images/title-left-bg.svg") no-repeat;
  }

  .right {
    display: flex;
    align-items: center;
  }
}

.content {
  display: flex;
  flex: 1;
  flex-direction: column;
  width: 100%;
  height: 95%;
  overflow: auto;
  overflow-y: auto;

  .d-table {
    flex-grow: 1;
    height: 100%;
    max-height: 100%;
    padding: 10px;
  }
}
</style>
